package com.lirisheng.repositories;

import com.lirisheng.domain.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 编写实现Repository接口的类,自动为其创建代理实现类,用来操作entity
 */
public interface MyRepository extends Repository<User,Long> {

//    @Modifying
//    @Query(value = " insert into  User (username,role) values (?1,?2) ",nativeQuery = true)
//    public void  save (String username,String role);

     public User save (User user);

    /**
     * 使用 derived method (method name) 具体的解析和命名规则
     *  链接:https://docs.spring.io/spring-data/jpa/docs/2.2.7.RELEASE/reference/html/#jpa.query-methods.named-queries
     *
     * @param username
     * @return
     */
    public User findByUsername(String username);


    /**
     * Using JPA Named Queries
     *
     * @return
     */
    public Collection<User> findAllByRole(String role);



    /**
     *
     * 注意:@Modifying:就是标识该语句为update语句,而不是query(delete也需要该注解来标识)
     * 	 属性 clearAutomatically:默认值为false,即entity实体没有得到删除,这会导致在执行update 语句之后,entityManage 包含的entity并没有得到更新(即没有
     * 	 跟数据库同步),如果想要得到及时的更新,则设置为true,意味的自动清除
     *
     * 也可以使用例如: @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
     *   User findByLastnameOrFirstname(@Param("lastname") String lastname,
     *                                  @Param("firstname") String firstname);
     *  来传递参数
     *
     *
     * @Modifying queries can only use void or int/Integer as return type
     *
     * 对于delete或者update的query,需要事务,即transational,才能执行,要不然则报错
     *
     *
     * @param role
     * @param username
     * @return
     */
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("update  User u set u.role= ?1 where  u.username= ?2 ")
    public int updateByUsername(String role, String username);


    public User deleteByUsername(User user);
}
